package com.grouuu.tile;

import nme.errors.Error;
import starling.display.BlendMode;
import starling.display.Image;
import starling.display.MovieClip;
import starling.textures.Texture;

/**
 * ...
 * @author Grouuu
 */

class TileGraphic 
{
	public var idTile(default, null):Int;
	public var animated(default, null):Bool = false;
	
	private var _img:Image;
	private var _mc:MovieClip;
	private var _bufferImage:flash.Vector<Image>;

	public function new(idTile:Int, textures:flash.Vector<Texture>) 
	{
		this.idTile = idTile;
		
		init(textures);
	}
	
	private function init(textures:flash.Vector<Texture>):Void
	{
		if (textures.length == 0)
		{
			trace("ERROR : texture null");
			
			return;
		}
		
		if (textures.length == 1)
		{
			try
			{
				_img = new Image(textures[0]);
				_img.blendMode = BlendMode.NONE;
				_img.touchable = false;
			}
			catch (error:Error)
			{
				trace("bad texture");
			}
		}
		else
		{
			animated = true;
			
			_bufferImage = new flash.Vector<Image>(textures.length);
			
			_mc = new MovieClip(textures);
			
			_mc.blendMode = BlendMode.NONE;
			_mc.touchable = false;
		}
		
		start();
	}
	
	// CONTROLS ///////////////////////////////////////////////////////////////////////////////
	
	public function nextFrame():Void
	{
		_mc.currentFrame = (_mc.currentFrame == _mc.numFrames - 1) ? 0 : _mc.currentFrame + 1;
	}
	
	public function start():Void
	{
		if (_mc != null)
			_mc.currentFrame = 0;
	}
	
	public function reset():Void
	{
		
	}
	
	// GETTER / SETTER ////////////////////////////////////////////////////////////////////////
	
	public function image():Image
	{
		if (_img != null)
			return _img;
		
		var currentFrame:Int = _mc.currentFrame;
		
		nextFrame();
		
		if (_bufferImage[currentFrame] == null)
			_bufferImage[currentFrame] = new Image(_mc.texture);
		
		return _bufferImage[currentFrame];
	}
	
	public function isPassable():Bool
	{
		return (idTile == 8);
	}
}